from django.shortcuts import render
from django.views import View
from areas.models import Area
from django import http
from meiduo_mall.utils.response_code import RET
from django.core.cache import cache

# Create your views here.


class AddressesView(View):
    def get(self, request):
        
        # 获取参数
        area_id = request.GET.get("area_id")
        if not area_id:
            
            # 判断是否有缓存
            province_list = cache.get('province_list')
            
            if province_list:
                data_dict = {
                "code": RET.OK,
                "province_list": province_list
                }
                return http.JsonResponse(data_dict)
            province = Area.objects.filter(parent=None).all()
            province_list = [{"id":item.id, "name": item.name} for item in province]
            data_dict = {
                "code": RET.OK,
                "province_list": province_list
            }
            
            # 设置缓存
            cache.set('province_list', province_list)
            
            return http.JsonResponse(data_dict)
        
        else:
            # 判断是否有缓存
            subs = cache.get('subs_%s' % area_id)
            if subs:
                data_dict = {
                "code": RET.OK,
                "sub_data": {
                    "subs": subs
                    }
                }
                return http.JsonResponse(data_dict)
            # 根据省的ID获取市
            cities = Area.objects.filter(parent_id=area_id).all()
            subs = [{"id": city.id, "name": city.name} for city in cities]
            
            # 拼接数据
            data_dict = {
                "code": RET.OK,
                "sub_data": {
                    "subs": subs
                }
            }
            
            # 设置缓存
            cache.set('subs_%s' % area_id, subs)
            # 返回响应
            return http.JsonResponse(data_dict)
        
        
        
        
        
        
        
        
        
        
        
        
        